Web Front End Note

Meow King February 22, 2024 Updated: February 22, 2024 #web #front-end

Nuxt && Vue

  1. Use function as useFetch parameter to watch URL change:
const { data: product, pending, error } = await useFetch(() => `https://dummyjson.com/products/${id.value}`)

/* Same as:
const { data: product, pending, error } = await useAsyncData(() => {
return $fetch(`https://dummyjson.com/products/${id.value}`)
}, {
watch: [id]
})
*/

JavaScript & TypeScript

Add a asynchronous function to event listener

use void to make the promise void (or you can use catch);

  share_btn?.addEventListener("click", () => { void share(); });

TypeScript

Configuration

Make window object available:

tsconfig.json:

"typeRoots": ["./node_modules/@types", "./src/static/js/types"],

then in one ts file inside the file path, do things like this:

import * as XLSX from 'xlsx';
import State from '../lib/state.ts';

declare global {
  interface Window {
    XLSX: typeof XLSX,
    workbook: XLSX.WorkBook | null,
    res_workbook: XLSX.WorkBook | null,
    ssp_state: State | null,
  }
}

Catch Error Type

try {
  await navigator.clipboard.writeText(url);
  show_dialog("Copy Successfully", "The URL link is successfully copied to your clipboard!");
} catch (error) {
  if (error instanceof Error) {
    console.error(error.message);
    show_dialog("Error", `${error.message}`);
  }
}

JSON

How to Cast a JSON Object to a Class in TypeScript
You can combine the above approaches with type guard function like this one

The one that I'm currently using:

  static from_json(json: unknown) : State | null {
    const obj =  new State();
    if (typeof json == 'object' && json != null
      && 'code' in json) {
        Object.assign(obj, json);
        return obj;
      }
    
    return null;
  }

Destructure a method from an object.

Instead of doing

const { decode_range } = XLSX.utils;

Do this:

// const { decode_range } = XLSX.utils;
const decode_range = (...args: Parameters<typeof XLSX.utils.decode_range>) => XLSX.utils.decode_range(...args);

Since the first may cause unintentional scoping of this according to eslint:

error  Avoid referencing unbound methods which may cause unintentional scoping of `this`.
If your function does not access `this`, you can annotate it with `this: void`, or consider using an arrow function instead  @typescript-eslint/unbound-method